
import random
from typing import TYPE_CHECKING, Any, Dict, Optional, Tuple
from const import (
    GRID_CELL_CLICKED_EVENT,
    SKILL_BUTTON_CLICKED_EVENT,
    TURN_START_EVENT,
    TURN_END_EVENT,
    Skill,
)
from model import Model, GridManager, Player, PlayerManager
from view import View
import pygame
from .util import InputHandler, WinChecker
from .skill import PowerupHandler
from .event import EventSystem
from const import TIME_LIMIT_START_EVENT, TIME_LIMIT_END_EVENT, TIME_LIMIT_RUNNING_EVENT








class Controller:

    
    model: Model # 游戏模型
    view: View # 游戏视图
    event_system: EventSystem # 事件系统
    powerup_handler: PowerupHandler # 技能处理器
    win_checker: WinChecker # 胜利检查器
    
    input_handler: InputHandler # 输入处理器

    
    
    """
    游戏主控制器，整合输入处理和游戏系统
    """
    def __init__(self, model: Model, view: View):
        self.model = model
        self.view = view
        # 初始化游戏状态
        self.init()
        self.time_limit_seconds = 10
        self.time_limit_start_ticks = None


    def init(self) -> None:
        """
        初始化游戏
        """
        # 重置限时相关定时器
        pygame.time.set_timer(TIME_LIMIT_RUNNING_EVENT, 0)
        self.time_limit_start_ticks = None

        # 重置组件
        self.model.init()
        self.powerup_handler = PowerupHandler(self.model)
        self.event_system = EventSystem()
        self.win_checker = WinChecker()

        

        

    def handle_event(self, event: pygame.event.Event) -> None:
        """
        处理事件
        """

        if self.model.game_over == True:
            return

        if event.type == TURN_START_EVENT:
            

            # 交换玩家
            self.model.player_manager.switch_player()

            # 事件系统进入下一回合
            self.event_system.next_turn()

            # 触发随机事件
            self.model.event_message = self.event_system.trigger_event(self.model)
            return

        if event.type == TURN_END_EVENT:
            self.handle_turn()

        
        if event.type == GRID_CELL_CLICKED_EVENT:

            cell = event.grid_coord
            
            # 处理技能使用或棋子放置
            if self.powerup_handler.current_skill:
                success = self.powerup_handler.activate_powerup(
                    self.model, cell, self.model.player_manager.current_player)

                if success:
                    print("技能使用成功！")

                    self.powerup_handler.end_skill_state()  # 重置选中的技能

                    pygame.event.post(pygame.event.Event(TURN_END_EVENT))  # 结束当前回合
                else:
                    print("技能未使用！")
            else:
                success = self.model.grid_manager.place_piece(cell, self.model.player_manager.current_player)

                if not success:
                    print("棋子放置失败！")
                else:
                    pygame.event.post(pygame.event.Event(TURN_END_EVENT))  # 结束当前回合
            
            return

        if event.type == SKILL_BUTTON_CLICKED_EVENT:

            self.powerup_handler.handle_skill_select(event.skill)

            return

        if event.type == TIME_LIMIT_START_EVENT:
            self.model.event_message = f"Timed round: {self.time_limit_seconds} seconds left"
            self.time_limit_start_ticks = pygame.time.get_ticks()
            # 每200ms触发一次TIME_LIMIT_RUNNING_EVENT
            pygame.time.set_timer(TIME_LIMIT_RUNNING_EVENT, 200)
            return

        if event.type == TIME_LIMIT_RUNNING_EVENT:
            now = pygame.time.get_ticks()
            elapsed = (now - self.time_limit_start_ticks) // 1000
            remain = max(0, self.time_limit_seconds - elapsed)
            if remain > 0:
                self.model.event_message = f"Timed round: {remain} seconds left"
            else:
                self.model.event_message = "Timeout! Automatically moving to next turn"
                pygame.time.set_timer(TIME_LIMIT_RUNNING_EVENT, 0)
                pygame.event.post(pygame.event.Event(TIME_LIMIT_END_EVENT))
            return

        if event.type == TIME_LIMIT_END_EVENT:
            # Timeout handling: random move or directly go to next turn
            self.model.event_message = "Timeout! Automatically moving to next turn"
            pygame.time.set_timer(TIME_LIMIT_RUNNING_EVENT, 0)
            pygame.event.post(pygame.event.Event(TURN_START_EVENT))
            return

    def handle_turn(self) -> None:
        """
        修改后的回合处理
        """
        # 取消限时倒计时事件
        pygame.time.set_timer(TIME_LIMIT_RUNNING_EVENT, 0)

        # 检查胜利
        winner_symbol = self.win_checker.check_win(self.model.grid_manager)
        if winner_symbol:
            self.model.game_over = True
            self.model.winner = winner_symbol

            return
        
        # 检查是否需要扩展网格
        if self.model.grid_manager.is_full():
            self.model.grid_manager.expand_grid()

        pygame.event.post(pygame.event.Event(TURN_START_EVENT))  # 开始新回合
        
